package com.senac.faces;


import java.util.List;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import com.senac.model.Usuario;
import com.senac.service.UsuarioBeanLocal;


@ManagedBean(name="userMBean")
@RequestScoped
public class UsuarioMBean {

	@EJB
	private UsuarioBeanLocal service;

	private Usuario user = new Usuario();
	private List<Usuario> list;
	private Integer userId;
	
	public String doSave() {
		try {
			service.save(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "usuarios";
	}
	
	public Usuario getUser() {
		return user;
	}

	public void setUser(Usuario user) {
		this.user = user;
	}

	public UsuarioBeanLocal getService() {
		return service;
	}

	public void setService(UsuarioBeanLocal service) {
		this.service = service;
	}
	
	public List<Usuario> getList() {
		if(list == null) {
			refreshList();
		}
		return list;
	}

	public void setList(List<Usuario> list) {
		this.list = list;
	}
	
	public Integer getUserId() {
		return userId;
	}

	public void setUserId(Integer userId) {
		this.userId = userId;
	}
	
	public String editar() {
		user = service.getById(userId);
		return "usuario";
	}
	
	public String remover() {
		service.delete(userId);
		refreshList();
		return "usuarios";
	}
	
	public String salvar() {
		try {
			service.save(user);	
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "usuarios";
	}
	
	private void refreshList() {
		list = service.get();
	}
	
}
